import pymysql
from bs4 import BeautifulSoup
import re

out_file = 'out.txt'
page = 100

if __name__ == '__main__':
    with open(out_file, "w", encoding="utf-8") as f:
        f.write("")

    with open(out_file, "a", encoding="utf-8") as f:
        db = pymysql.connect(host="localhost", port=3306, user="root", password="123456", database="y_site")

        cursor = db.cursor()  # 创建游标对象

        sql = 'select cate,title,content from story2 order by cate,title'  # sql语句

        num = cursor.execute(sql)  # 执行sql语句

        # cate = ""
        for i in range(num):
            cate,title,content = cursor.fetchone()  # 获取一条数据

            content = content.replace(" ","").replace("<","\r\n<").replace("<br>","\r\n").replace("\r\n\r\n","\r\n").replace("\r\n\r\n","\r\n")
            t = re.match(r'第(.{1,9})章', content)
            if(t != None) :
                content = content.replace("章", " 章")

            bsobj = BeautifulSoup(content, 'lxml')
            f.write("第{}章 {}\r\n".format(str(i+1),title))
            f.write(bsobj.text)
            f.write("\r\n")

            print(str(i),'/',str(num))

        cursor.close()
        db.close()  # 关闭数据库的连接



